package com.zzjson.util;

import javax.crypto.*;
import javax.crypto.spec.DESedeKeySpec;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.util.Base64;

public class DESCodec {
	private static final String DES_ECB_ALGORITHM = "DESede/ECB/PKCS5Padding";
	private static final String defaultCharset = "UTF-8";

	public static String encode(String source, String key)
			throws InvalidKeyException, UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeySpecException,
			NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
		final DESedeKeySpec dks = new DESedeKeySpec(key.getBytes(defaultCharset));
		final SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESede");
		final SecretKey securekey = keyFactory.generateSecret(dks);
		final Cipher cipher = Cipher.getInstance(DES_ECB_ALGORITHM);
		cipher.init(Cipher.ENCRYPT_MODE, securekey);
		final byte[] valueByte = cipher.doFinal(URLEncoder.encode(source, defaultCharset).getBytes());
		final Base64.Encoder encoder = Base64.getEncoder();
		return encoder.encodeToString(valueByte);
	}

	public static String decode(String source, String key)
			throws InvalidKeyException, UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeySpecException,
			NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
		byte[] encoded = Base64.getDecoder().decode(source);
		DESedeKeySpec desKey = new DESedeKeySpec(key.getBytes(defaultCharset));
		SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESede");
		SecretKey securekey = keyFactory.generateSecret(desKey);
		Cipher cipher = Cipher.getInstance(DES_ECB_ALGORITHM);
		cipher.init(Cipher.DECRYPT_MODE, securekey);
		byte[] decoded = cipher.doFinal(encoded);
		return URLDecoder.decode(new String(decoded), defaultCharset);
	}
}
